import dayjs from 'dayjs';
import { ref } from 'vue';
import { getTimePeriod } from '@/utils/date.utils';
import { useIntervalFn } from './useIntervalFn';
import { useTimeoutFn } from './useTimeoutFn';

export function useAccurateTimePeriod(delay = 1000) {
  const dateNow = ref(dayjs());
  const timePeriod = ref(getTimePeriod(dateNow.value.toDate()));

  const now = dayjs();
  const elapsed = now.valueOf() % delay;
  const delayToNextTick = delay - elapsed;

  useTimeoutFn(() => {
    dateNow.value = dayjs();
    timePeriod.value = getTimePeriod(dateNow.value.toDate());

    useIntervalFn(() => {
      dateNow.value = dayjs();
      timePeriod.value = getTimePeriod(dateNow.value.toDate());
    }, delay);
  }, delayToNextTick);

  return {
    dateNow,
    timePeriod
  };
}
